<?php

namespace app\zyhsapi\controller\v5;

use app\aliyun\controller\AliyunFilterWord;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\comment\ZyhsArticleComment;
use app\zyhsapi\model\comment\ZyhsArticleCommentGood;
use app\zyhsapi\model\comment\ZyhsArticleCommentReply;
use app\zyhsapi\model\comment\ZyhsNoComment;
use app\zyhsapi\model\ZyhsAstrBindUser;
use app\zyhsapi\model\ZyhsInteractiveMessage;
use app\zyhsapi\model\ZyhsPxyzUserQuestion;
use think\response\Json;

class ContentComment extends ZyhsAuth
{
    /**
     * 添加评论
     * @return Json
     * @throws \Exception
     */
    public function commentAdd()
    {
        $id = input('id/d', 0);
        $content = trim(input('content/s', ''));
        if (!$id || empty($content))
        {
            return show(config('code.error'), '请求异常，请重试～');
        }
        if (mb_strlen($content) > 80)
        {
            return show(config('code.error'), '发表的看法最多输入80字～');
        }
        if (Util::commentCheck($this->user['id'], [
            'action' => 'commentAdd',
            'content' => $content,
            'id' => $id,
        ]))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }
        //禁言判断
        $noCommentList = (new ZyhsNoComment())->getNoCommentList(1);
        if (in_array($this->user['id'], $noCommentList, true))
        {
            return show(config('code.error'), '你已被禁言，不可发布内容');
        }
        //内容安全检测
        $res = AliyunFilterWord::checkText($content, 'article_comment');
        // 若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            return show(201, '内容涉嫌' . $res['label']);
        }
        $data = [
            'uid' => $this->user['id'],
            'status' => 1,
            'type' => 1,
            'aid' => $id,
            'good_num' => 0,
            'content' => $content,
            'reply_num' => 0,
            'create_time' => $this->request->time(),
        ];

        $resData = (new ZyhsArticleComment())->commentAdd($this->user, $data);

        if ($resData['status'])
        {
            return show(config('code.success'), '请求成功', $resData['data']);
        } else
        {
            return show(config('code.error'), $resData['msg']);
        }
    }

    /**
     * 回复评论
     * @return Json
     * @throws \Exception
     */
    public function commentReplyAdd()
    {
        $id = input('id/d', 0);
        $pid = input('pid/d', 0);
        $content = trim(input('content/s', ''));
        if (!$id || empty($content))
        {
            return show(config('code.error'), '请求异常，请重试～');
        }
        if (mb_strlen($content) > 20)
        {
            return show(config('code.error'), '发表的看法最多输入20字～');
        }
        if (Util::commentCheck($this->user['id'], [
            'action' => 'commentReplyAdd',
            'content' => $content,
            'pid' => $pid,
            'id' => $id,
        ]))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }
        //禁言判断
        $noCommentList = (new ZyhsNoComment())->getNoCommentList(1);
        if (in_array($this->user['id'], $noCommentList, true))
        {
            return show(config('code.error'), '你已被禁言，不可发布内容');
        }
        //内容安全检测
        $res = AliyunFilterWord::checkText($content, 'article_comment');
        // 若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            return show(201, '内容涉嫌' . $res['label']);
        }
        $data = [
            'comment_id' => $id,
            'uid' => $this->user['id'],
            'pid' => $pid,
            'content' => $content,
            'good_num' => 0,
            'status' => 1,
            'create_time' => $this->request->time(),
        ];

        $resData = (new ZyhsArticleCommentReply())->replyAdd($this->user, $data);

        if ($resData['status'])
        {
            return show(config('code.success'), '请求成功', $resData['data']);
        } else
        {
            return show(config('code.error'), $resData['msg']);
        }
    }

    /**
     * 获取 评论列表
     * @return Json
     */
    public function getCommentList()
    {
        $id = input('id/d', 0); // 内容ID
        $minId = input('min_id/d', 0);
        $type = input('type/d', 1); // 1=>全部 2=>只看用户
        $aType = 1; //  内容类型  1=>平行宇宙

        if ($id <= 0 || $minId < 0 || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $resData = (new ZyhsArticleComment())->getCommentList($this->user ?: [], $aType, $id, $minId, $type);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 评论回复列表
     * @return Json
     */
    public function getCommentReplyList()
    {
        $id = input('id/d', 0); // 评论ID
        $minId = input('min_id/d', 0);
        $type = input('type/d', 1); // 1=>全部 2=>只看用户

        if ($id <= 0 || $minId < 0 || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $resData = (new ZyhsArticleCommentReply())->getCommentReplyList($this->user['id'] ?? 0, $id, $type, $minId);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 内容 与 评论 点赞
     * @return Json
     * @throws \Exception
     */
    public function commentZan()
    {
        $type = input('type/d', 0);
        $id = input('id/d', 0);
        $status = input('status/d', 1);
        if (!in_array($type, [1, 2], true) || $id <= 0 || !in_array($status, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsArticleCommentGoodModel = new ZyhsArticleCommentGood();
        $zyhsArticleCommentModel = new ZyhsArticleComment();
        $zyhsArticleCommentReplyModel = new ZyhsArticleCommentReply();
        if ($type === 1)
        {   // 评论 点赞
            $commentInfo = $zyhsArticleCommentModel->getInfoById($id, ['status', 'aid', 'type', 'uid', 'good_num', 'reply_num']);
            if (!$commentInfo || (!isset($commentInfo['status']) && $commentInfo['status'] !== 1))
            {
                return show(config('code.error'), '服务异常，评论内容不存在～');
            }
            $goodCommentIds = $zyhsArticleCommentGoodModel->getUserCommentGoodCids($this->user['id'], 1);
            $uid2 = $commentInfo['uid'];
            $goodNum = $commentInfo['good_num'];
            $commentId = $id;
            $crId = 0;
            $interactiveType = 5;
        } else
        {   // 评论回复 点赞
            $commentReplyInfo = $zyhsArticleCommentReplyModel->getInfoById($id, ['status', 'comment_id', 'uid', 'good_num']);
            if (!$commentReplyInfo || (!isset($commentReplyInfo['status']) && $commentReplyInfo['status'] !== 1))
            {
                return show(config('code.error'), '服务异常，评论内容不存在～');
            }
            $commentInfo = $zyhsArticleCommentModel->getInfoById($commentReplyInfo['comment_id'], ['status', 'aid', 'type']);
            if (!$commentInfo || (!isset($commentInfo['status']) && $commentInfo['status'] !== 1))
            {
                return show(config('code.error'), '服务异常，评论内容不存在～');
            }
            $goodCommentIds = $zyhsArticleCommentGoodModel->getUserCommentGoodCids($this->user['id'], 2);
            $uid2 = $commentReplyInfo['uid'];
            $goodNum = $commentReplyInfo['good_num'];
            $commentId = $commentReplyInfo['comment_id'];
            $crId = $id;
            $interactiveType = 6;
        }
        if ($status === 1)
        {   // 点赞
            if (in_array($id, $goodCommentIds, true))
            {
                return show(config('code.success'), '点赞成功');
            }
            $data = [
                'atype' => $commentInfo['type'],
                'aid' => $commentInfo['aid'],
                'ctype' => $type,
                'cr_id' => $id,
                'uid' => $this->user['id'],
                'uid2' => $uid2,
                'create_time' => $this->request->time(),
            ];
            $resData = $zyhsArticleCommentGoodModel->addZan($data);
        } else
        {
            if (!in_array($id, $goodCommentIds, true))
            {
                return show(config('code.success'), '取消点赞成功');
            }
            $data = [
                'ctype' => $type,
                'cr_id' => $id,
                'uid' => $this->user['id'],
            ];
            $resData = $zyhsArticleCommentGoodModel->delZan($data);
        }
        if ($resData)
        {
            $inc = $status === 1 ? 1 : -1;
            if ($type === 1)
            {   // 更新 评论 点赞数 ---------------------------------------------------------------
                $zyhsArticleCommentModel->updateReplyNumData($id, 'good_num', [
                    'good_num' => $goodNum,    // 点赞数
                    'reply_num' => $commentInfo['reply_num'], // 评论总数
                ], $inc);
            } else
            {   // 更新 评论回复 点赞数 ---------------------------------------------------------------
                $zyhsArticleCommentReplyModel->updateReplyGoodNum($id, $goodNum, $inc);
            }
            if ($uid2 !== $this->user['id'])
            {   //  不是自己给自己点赞的情况 添加 点赞 互动消息
                (new ZyhsInteractiveMessage())->setZanInteractiveMessage($commentInfo['type'], $commentInfo['aid'], $interactiveType, $uid2, $this->user['id'], $commentId, $crId);
            }
            return show(config('code.success'), $status === 1 ? '点赞成功' : '取消点赞成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    public function commentDel()
    {
        $type = input('type/d', 0);
        $id = input('id/d', 0);
        if (!in_array($type, [1, 2], true) || $id <= 0)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsArticleCommentModel = new ZyhsArticleComment();
        $zyhsArticleCommentReplyModel = new ZyhsArticleCommentReply();
        if ($type === 1)
        {   // 评论 删除
            $commentInfo = $zyhsArticleCommentModel->getInfoById($id, ['status', 'aid', 'type', 'uid', 'reply_num']);
            if (!$commentInfo || (isset($commentInfo['uid']) && $commentInfo['uid'] !== $this->user['id']))
            {
                return show(config('code.error'), '服务异常，评论内容不存在～');
            }
            if ($commentInfo['status'] !== 1)
            {
                return show(config('code.success'), '删除成功');
            }
            $res = $zyhsArticleCommentModel->commentDel($commentInfo['type'], $commentInfo['aid'], $id);
            if (!$res)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $commentReplyNum = $commentInfo['reply_num'];
        } else
        {   // 评论回复 删除
            $commentReplyInfo = $zyhsArticleCommentReplyModel->getInfoById($id, ['status', 'comment_id', 'uid', 'good_num']);
            if (!$commentReplyInfo || (isset($commentReplyInfo['uid']) && $commentReplyInfo['uid'] !== $this->user['id']))
            {
                return show(config('code.error'), '服务异常，评论内容不存在～');
            }
            if ($commentReplyInfo['status'] !== 1)
            {
                return show(config('code.success'), '删除成功');
            }
            $res = $zyhsArticleCommentReplyModel->replyDel($id, $commentReplyInfo['comment_id']);
            if (!$res)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $commentInfo = $zyhsArticleCommentModel->getInfoById($commentReplyInfo['comment_id'], ['status', 'aid', 'type', 'good_num', 'reply_num']);
            if (!$commentInfo || (!isset($commentInfo['status']) && $commentInfo['status'] !== 1))
            {   // 一级评论 已删除 直接返回【一级评论删除时，内容评论数已删除】 不用更新 内容和一级评论 评论数
                return show(config('code.success'), '删除成功');
            }
            //  更新 一级评论 评论数
            $zyhsArticleCommentModel->updateReplyNumData($commentReplyInfo['comment_id'], 'reply_num', [
                'good_num' => $commentInfo['good_num'],    // 点赞数
                'reply_num' => $commentInfo['reply_num'], // 评论总数
            ], -1);
            $commentReplyNum = 0;   // 删除评论回复 内容删除1条数据
        }
        switch ($commentInfo['type'])
        {
            case 1:
                $zyhsPxyzUserQuestionModel = new ZyhsPxyzUserQuestion();
                $contentDetail = $zyhsPxyzUserQuestionModel->getInfoById($commentInfo['aid'], ['status', 'comment_num', 'good_num', 'read_num', 'astr_reply_num']);
                if (!$contentDetail || (!isset($contentDetail['status']) && $contentDetail['status'] !== 1))
                {   // 内容 已经被删除了 不用更新 评论数
                    return show(config('code.success'), '删除成功');
                }
                $inc = ($commentReplyNum * -1) - 1;
                $data = [
                    'comment_num' => $contentDetail['comment_num'],
                    'good_num' => $contentDetail['good_num'],
                    'read_num' => $contentDetail['read_num'],
                ];
                if ($type === 1 && $contentDetail['astr_reply_num'] > 0)
                {   // 删除 一级评论
                    // 获取 用户绑定咨询师信息
                    $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
                    if (isset($userBindAstrInfo[$this->user['id']]))
                    {   // 自己是咨询师
                        $data['astr_reply_num'] = $contentDetail['astr_reply_num'] - 1;
                    }
                }
                //  更新 内容 的 评论数
                $zyhsPxyzUserQuestionModel->updateCommentNumData($commentInfo['aid'], 'comment_num', $data, $inc);
                break;
        }
        return show(config('code.success'), '删除成功');
    }
}
